<template>
  <div class="login-container">
    <!-- 终端风格的登录表单容器 -->
    <div class="terminal-box">
      <!-- 终端标题栏 -->
      <div class="terminal-header">
        <div class="terminal-buttons">
          <div class="button red"></div>
          <div class="button yellow"></div>
          <div class="button green"></div>
        </div>
        <div class="terminal-title">认证模块</div>
      </div>
      
      <!-- 登录表单 -->
      <div class="login-form-container">
        <h2 class="hacker-title">系统登录</h2>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          class="login-form hacker-form"
          label-position="left"
        >
          <el-form-item label="用户名" prop="username" class="hacker-form-item">
            <div class="input-wrapper">
              <el-input 
                v-model="loginForm.username" 
                placeholder="用户ID"
                prefix-icon="User" 
                class="hacker-input"
                @focus="inputFocus('username')"
                @blur="inputBlur('username')"
              >
              </el-input>
              <div class="input-glow" :class="{ active: focusedInput === 'username' }"></div>
            </div>
          </el-form-item>
          
          <el-form-item label="密码" prop="password" class="hacker-form-item">
            <div class="input-wrapper">
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="密码"
                prefix-icon="Lock" 
                class="hacker-input"
                @focus="inputFocus('password')"
                @blur="inputBlur('password')"
              >
              </el-input>
              <div class="input-glow" :class="{ active: focusedInput === 'password' }"></div>
            </div>
          </el-form-item>
          
          <!-- 验证码 -->
          <el-form-item label="验证码" prop="captcha" class="hacker-form-item">
            <div class="captcha-container">
              <div class="input-wrapper captcha-input-wrapper">
                <el-input 
                  v-model="loginForm.captcha" 
                  placeholder="输入验证码"
                  class="hacker-input captcha-input"
                  @focus="inputFocus('captcha')"
                  @blur="inputBlur('captcha')"
                >
                </el-input>
                <div class="input-glow" :class="{ active: focusedInput === 'captcha' }"></div>
              </div>
              <div class="captcha-image-wrapper" @click="generateCaptcha">
                <canvas 
                  ref="captchaCanvas"
                  class="captcha-canvas"
                  width="120" 
                  height="40"
                ></canvas>
                <span class="captcha-refresh-tip">点击刷新</span>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item class="hacker-form-item">
            <el-button 
              type="primary" 
              class="hacker-button login-button" 
              @click="handleLogin"
              :loading="isLoading"
            >
              <span v-if="!isLoading">登录系统</span>
              <span v-else>正在验证...</span>
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 登录状态提示 -->
        <div v-if="errorMsg" class="error-message">
          <el-icon class="error-icon"><Warning /></el-icon>
          {{ errorMsg }}
        </div>
        
        <!-- 系统状态信息 -->
        <div class="system-info">
          <span>系统状态: <span class="status-online">在线</span></span>
          <span>安全等级: <span class="security-level">高级</span></span>
        </div>
      </div>
    </div>
    
    <!-- 数字雨背景效果 -->
    <div class="matrix-rain"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import { User, Lock, Warning } from '@element-plus/icons-vue'

const router = useRouter()
const loginFormRef = ref()
const isLoading = ref(false)
const errorMsg = ref('')
const focusedInput = ref('')

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 验证码相关
const captchaCanvas = ref<HTMLCanvasElement>()
const captchaText = ref('')

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value.toLowerCase() !== captchaText.value.toLowerCase()) {
          callback(new Error('验证码不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 输入框聚焦处理
const inputFocus = (field: string) => {
  focusedInput.value = field
  // 添加黑客风格的输入日志
  console.log(`[INPUT] Focused on ${field}`)
}

// 输入框失焦处理
const inputBlur = (field: string) => {
  setTimeout(() => {
    focusedInput.value = ''
  }, 200)
}

// 生成验证码
const generateCaptcha = () => {
  if (!captchaCanvas.value) return
  
  const canvas = captchaCanvas.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 设置背景色
  ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 生成验证码文本
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaText.value = code
  
  // 绘制验证码文本
  ctx.font = 'bold 24px Courier New'
  
  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgba(0, 255, 65, ${Math.random() * 0.5 + 0.2})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineWidth = Math.random() * 2
    ctx.stroke()
  }
  
  // 绘制干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgba(0, 255, 65, ${Math.random() * 0.5 + 0.3})`
    ctx.beginPath()
    ctx.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      Math.random() * 1.5,
      0,
      Math.PI * 2
    )
    ctx.fill()
  }
  
  // 绘制验证码文本（添加倾斜效果）
  const textWidth = ctx.measureText(code).width
  const x = (canvas.width - textWidth) / 2 - 10
  const y = canvas.height / 2 + 10
  
  for (let i = 0; i < code.length; i++) {
    const char = code.charAt(i)
    const charWidth = ctx.measureText(char).width
    
    ctx.fillStyle = `rgba(0, 255, 65, ${Math.random() * 0.3 + 0.7})`
    ctx.save()
    ctx.translate(x + i * (charWidth + 5), y)
    ctx.rotate((Math.random() - 0.5) * 0.5) // 随机旋转角度
    ctx.fillText(char, 0, 0)
    ctx.restore()
  }
  
  // 添加系统日志
  console.log('[CAPTCHA] New captcha generated')
  loginForm.captcha = '' // 清空输入框
}

// 处理登录
const handleLogin = async () => {
  // 清除之前的错误信息
  errorMsg.value = ''
  
  // 表单验证
  if (!loginFormRef.value) return
  
  try {
    // 验证表单
    await loginFormRef.value.validate()
    
    // 设置加载状态
    isLoading.value = true
    
    // 添加黑客风格的登录尝试日志
    console.log(`[AUTH] Login attempt by user: ${loginForm.username}`)
    console.log(`[AUTH] Captcha verification: ${loginForm.captcha}`)
    
    // 模拟登录请求延迟
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 这里是模拟登录逻辑，实际项目中应该替换为真实的登录API调用
    if (loginForm.username && loginForm.password && loginForm.captcha) {
      // 存储用户信息（实际项目中应该使用更安全的方式）
      localStorage.setItem('user', JSON.stringify({
        username: loginForm.username,
        token: 'mock-token-' + Date.now()
      }))
      
      // 登录成功日志
      console.log(`[AUTH] Login successful for user: ${loginForm.username}`)
      
      // 显示成功消息
      ElMessage.success('登录成功，正在进入系统...')
      
      // 跳转到主页面
      router.push('/main')
    } else {
      // 登录失败处理
      throw new Error('用户名或密码错误')
    }
  } catch (error) {
    // 登录失败日志
    console.error(`[AUTH] Login failed for user: ${loginForm.username}`, error)
    
    // 设置错误信息
    errorMsg.value = error instanceof Error ? error.message : '登录失败，请重试'
    
    // 添加故障动画效果
    const terminalBox = document.querySelector('.terminal-box')
    if (terminalBox) {
      terminalBox.classList.add('glitch-effect')
      setTimeout(() => {
        terminalBox.classList.remove('glitch-effect')
      }, 500)
    }
  } finally {
    // 重置加载状态
    isLoading.value = false
  }
}

// 添加键盘快捷键支持（黑客风格）
onMounted(() => {
  // 系统初始化日志
  console.log('[SYSTEM] Login module initialized')
  console.log('[SYSTEM] Authentication protocol v2.3 active')
  console.log('[SYSTEM] Captcha system initialized')
  
  // 生成初始验证码
  setTimeout(() => {
    generateCaptcha()
  }, 100)
  
  // 键盘事件监听
  const handleKeyDown = (e: KeyboardEvent) => {
    // Ctrl/Cmd + Enter 登录
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
      e.preventDefault()
      handleLogin()
    }
    
    // F12 显示系统信息（模拟）
    if (e.key === 'F12') {
      e.preventDefault()
      console.log('[SYSTEM] Debug info:')
      console.log('- Security: AES-256 encryption enabled')
      console.log('- Connection: SSL/TLS secured')
      console.log('- Protocol: v2.3')
    }
  }
  
  window.addEventListener('keydown', handleKeyDown)
  
  // 清理函数
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown)
    console.log('[SYSTEM] Login module terminated')
  })
  
  // 创建数字雨效果
  createMatrixRain()
})

// 数字雨效果函数
const createMatrixRain = () => {
  const matrixRain = document.querySelector('.matrix-rain')
  if (!matrixRain) return
  
  // 这里可以实现数字雨效果的逻辑
  // 为简化，这里只添加一些基础的字符动画
  const chars = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン01010101'
  
  for (let i = 0; i < 100; i++) {
    const charElement = document.createElement('div')
    charElement.classList.add('matrix-char')
    charElement.textContent = chars[Math.floor(Math.random() * chars.length)]
    charElement.style.left = `${Math.random() * 100}%`
    charElement.style.top = `${Math.random() * 100}%`
    charElement.style.fontSize = `${Math.random() * 10 + 8}px`
    charElement.style.animationDuration = `${Math.random() * 10 + 10}s`
    charElement.style.animationDelay = `${Math.random() * 5}s`
    matrixRain.appendChild(charElement)
  }
}
</script>

<style scoped>
/* 登录容器 */
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--hacker-panel-dark);
  position: relative;
  overflow: hidden;
  /* 黑客风格网格背景 */
  background-image: 
    linear-gradient(rgba(0, 255, 65, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 65, 0.05) 1px, transparent 1px);
  background-size: 30px 30px;
}

/* 终端风格的登录框 */
.terminal-box {
  background-color: var(--hacker-panel);
  border: 1px solid var(--hacker-border);
  border-radius: 4px;
  box-shadow: 
    0 0 15px rgba(0, 255, 65, 0.2),
    0 0 30px rgba(0, 0, 0, 0.5);
  width: 400px;
  max-width: 90vw;
  overflow: hidden;
  position: relative;
  z-index: 10;
}

/* 终端标题栏 */
.terminal-header {
  height: 28px;
  background-color: var(--hacker-panel-dark);
  border-bottom: 1px solid var(--hacker-border);
  display: flex;
  align-items: center;
  padding: 0 10px;
}

/* 终端窗口按钮 */
.terminal-buttons {
  display: flex;
  gap: 6px;
  margin-right: 10px;
}

.terminal-buttons .button {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.terminal-buttons .button.red {
  background-color: #ff5f56;
}

.terminal-buttons .button.yellow {
  background-color: #ffbd2e;
}

.terminal-buttons .button.green {
  background-color: #27c93f;
}

/* 终端标题 */
.terminal-title {
  flex: 1;
  color: var(--hacker-green);
  font-size: 12px;
  font-family: 'Courier New', monospace;
  text-align: center;
  letter-spacing: 1px;
}

/* 登录表单容器 */
.login-form-container {
  padding: 30px;
}

/* 黑客风格标题 */
.hacker-title {
  color: var(--hacker-green);
  text-align: center;
  font-family: 'Courier New', monospace;
  font-size: 24px;
  margin-bottom: 30px;
  letter-spacing: 2px;
  text-shadow: 0 0 8px var(--hacker-green-glow);
}

/* 黑客风格表单 */
.hacker-form {
  color: var(--hacker-text);
}

.hacker-form-item {
  margin-bottom: 20px;
}

.hacker-form .el-form-item__label {
  color: var(--hacker-green);
  font-family: 'Courier New', monospace;
  font-size: 14px;
  letter-spacing: 1px;
}

/* 输入框样式 */
.input-wrapper {
  position: relative;
}

.hacker-input {
  background-color: rgba(0, 0, 0, 0.5);
  border: 1px solid var(--hacker-border);
  color: var(--hacker-green) !important;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  letter-spacing: 1px;
  transition: all 0.3s ease;
  border-radius: 0;
}

.hacker-input:hover {
  border-color: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}

.hacker-input:focus {
  border-color: var(--hacker-green);
  box-shadow: 0 0 12px var(--hacker-green-glow);
  background-color: rgba(0, 0, 0, 0.7);
}

.hacker-input::placeholder {
  color: rgba(0, 255, 65, 0.5);
  font-family: 'Courier New', monospace;
  letter-spacing: 1px;
}

/* 输入框发光效果 */
.input-glow {
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border: 2px solid transparent;
  border-radius: 2px;
  pointer-events: none;
  transition: all 0.3s ease;
}

.input-glow.active {
  border-color: var(--hacker-green);
  box-shadow: 0 0 15px var(--hacker-green-glow);
  animation: glowPulse 2s infinite alternate;
}

/* 登录按钮 */
.hacker-button {
  background-color: var(--hacker-green-dark);
  border: 1px solid var(--hacker-green);
  color: var(--hacker-panel-dark);
  font-family: 'Courier New', monospace;
  font-size: 16px;
  letter-spacing: 2px;
  text-transform: uppercase;
  padding: 12px 20px;
  transition: all 0.3s ease;
  border-radius: 0;
  width: 100%;
  text-shadow: 0 0 5px rgba(0, 255, 65, 0.5);
}

.hacker-button:hover {
  background-color: var(--hacker-green);
  box-shadow: 0 0 15px var(--hacker-green-glow);
  transform: translateY(-2px);
}

.hacker-button:active {
  transform: translateY(0);
}

.hacker-button:disabled {
  background-color: var(--hacker-border);
  border-color: var(--hacker-border);
  color: var(--hacker-text);
  box-shadow: none;
  transform: none;
}

/* 错误消息 */
.error-message {
  background-color: rgba(255, 0, 0, 0.1);
  border: 1px solid rgba(255, 0, 0, 0.3);
  color: #ff6b6b;
  padding: 10px 15px;
  margin-top: 15px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 10px;
  animation: shake 0.5s ease-in-out;
}

.error-icon {
  color: #ff6b6b;
}

/* 验证码容器 */
.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input-wrapper {
  flex: 1;
}

.captcha-input {
  width: 100%;
}

.captcha-image-wrapper {
  position: relative;
  cursor: pointer;
  user-select: none;
}

.captcha-canvas {
  border: 1px solid var(--hacker-border);
  background-color: rgba(0, 0, 0, 0.5);
  display: block;
}

.captcha-image-wrapper:hover .captcha-canvas {
  border-color: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}

.captcha-refresh-tip {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: var(--hacker-text);
  font-family: 'Courier New', monospace;
  opacity: 0;
  transition: opacity 0.3s;
  white-space: nowrap;
}

.captcha-image-wrapper:hover .captcha-refresh-tip {
  opacity: 1;
}

/* 系统信息 */
.system-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--hacker-border);
  display: flex;
  justify-content: space-between;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: var(--hacker-text);
}

.status-online {
  color: var(--hacker-green);
  font-weight: bold;
}

.security-level {
  color: #ffbd2e;
  font-weight: bold;
}

/* 数字雨效果 */
.matrix-rain {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.matrix-char {
  position: absolute;
  color: rgba(0, 255, 65, 0.2);
  font-family: 'Courier New', monospace;
  opacity: 0;
  animation: matrixRain linear infinite;
  transform-origin: 0 0;
}

/* 动画效果 */
@keyframes matrixRain {
  0% {
    transform: translateY(-10%) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 0.5;
  }
  90% {
    opacity: 0.5;
  }
  100% {
    transform: translateY(110%) rotate(10deg);
    opacity: 0;
  }
}

@keyframes glowPulse {
  0% {
    box-shadow: 0 0 10px var(--hacker-green-glow);
  }
  100% {
    box-shadow: 0 0 20px var(--hacker-green-glow), 0 0 30px rgba(0, 255, 65, 0.3);
  }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

@keyframes glitch-effect {
  0% { transform: translate(0); }
  20% { transform: translate(-2px, 2px); box-shadow: 0 0 20px rgba(255, 0, 0, 0.5); }
  40% { transform: translate(-2px, -2px); box-shadow: 0 0 20px rgba(255, 0, 0, 0.5); }
  60% { transform: translate(2px, 2px); box-shadow: 0 0 20px rgba(255, 0, 0, 0.5); }
  80% { transform: translate(2px, -2px); box-shadow: 0 0 20px rgba(255, 0, 0, 0.5); }
  100% { transform: translate(0); box-shadow: 0 0 15px rgba(0, 255, 65, 0.2); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .terminal-box {
    width: 90vw;
    margin: 20px;
  }
  
  .login-form-container {
    padding: 20px;
  }
  
  .hacker-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .system-info {
    flex-direction: column;
    gap: 10px;
  }
}

/* 自定义滚动条（如果需要） */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--hacker-panel-dark);
}

::-webkit-scrollbar-thumb {
  background: var(--hacker-green-dark);
  border: 1px solid var(--hacker-green-glow);
}

::-webkit-scrollbar-thumb:hover {
  background: var(--hacker-green);
  box-shadow: 0 0 8px var(--hacker-green-glow);
}
</style>
